import time, redis, json
from datetime import datetime
from decimal import Decimal
from flask import Blueprint, jsonify, request, session
from ..extensions import qhjy_db, jys_db, pool
from ..utils.binance import getETHBinance, getETHBinanceForOne
from ..utils.computeGains import compute_gains
from ..utils.token import check_activate_token
from ..utils.decimal_to_float import decimal_to_float

eth_qhjy = Blueprint('eth_qhjy', __name__)


# 最近十期七家交易所BTC数据
@eth_qhjy.route('/result/', methods=['GET', 'POST'])
def result():
    sql = "select id,nper,result,result_rate from qh_nper where is_current!=1 and result!=0 and coin_id=24 order by id desc limit 10"
    # sql='select qh_result.*,qh_nper.nper,qh_nper.result,qh_nper.result_rate from qh_result INNER  join qh_nper on qh_result.nper_id=qh_nper.id where qh_nper.coin_id=3 and qh_nper.is_current in (0,2) and qh_nper.id in (select A.id from (select id from qh_nper where qh_nper.coin_id=3 and is_current in (0,2) ORDER by id DESC limit 10) as A) '
    npers = qhjy_db.selectall(sql)
    # print(npers)
    mlist = []
    if npers:
        for nper in npers:
            sql = 'select * from qh_result where nper_id=%d and exchange_name in (1,2,3,6,7) GROUP by exchange_name ORDER by exchange_name' % (
            nper["id"])
            datas = qhjy_db.selectall(sql)
            if datas:
                for r in datas:
                    if r:
                        r['rose'], r["consequence"] = compute_gains(r['open_time_price'], r['end_time_price'])
                        r["result"] = nper["result"]
                        r["result_rate"] = nper["result_rate"]
                        r["nper"] = nper["nper"]
                        for k, v in r.items():
                            if isinstance(v, Decimal):
                                r[k] = str(round(v, 2))

                mlist.append({nper["nper"]: datas})
        return jsonify({'code': 1, 'datas': mlist, 'msg': '返回最新十期数据'})
    else:
        return jsonify({'code': 0, 'datas': '', 'msg': '数据出错了'})


# 买涨,买平,买跌
@eth_qhjy.route('/operation/<int:uid>/', methods=['GET', 'POST'])
def operation(uid):
    # 检查是否开盘时间
    m = (datetime.now().minute) % 10
    s = datetime.now().second
    if m == 4 and s in range(50, 60):
        return jsonify({'code': 0, 'data': '', 'msg': '现在不是开盘时间 请等待开盘'})
    # 获得配置参数
    config = qhjy_db.selectone('select is_open,btc_error,eth_error from qh_config')
    if not config['is_open']:
        return jsonify({'code': 0, 'data': '', 'msg': '现在不是开盘时间 请等待开盘'})
    if config['eth_error'] == 1:
        return jsonify({'code': 0, 'data': '', 'msg': 'ETH正在维护中'})
    # 获取投注价格
    try:
        price = Decimal(request.form.get('price'))
    except:
        return jsonify({'code': 0, 'data': '', 'msg': '非法数据,请重新输入'})
    token = request.cookies.get('token')
    if token and check_activate_token(token) == session['id']:
        user_id = session["id"]
        # 从连接池中获取redis
        redis_store = redis.Redis(connection_pool=pool)
        # 获取资金情况
        finance = jys_db.selectone('select * from bf_user_coin where userid=%d' % int(user_id))
        # 获取该期数据情况
        nper = qhjy_db.selectone('select * from qh_nper where coin_id=24 and is_current = 1')
        nper_id = nper["id"]
        # 检查余额是否充足
        if price > finance["eth"]:
            return jsonify({'code': 0, 'data': '', 'msg': 'ETH余额不足'})
        mobile = str(session["mobile"])[:3] + '****' + str(session["mobile"])[:7]
        # redis记录投注总金额
        if uid == 1:
            up_price = float(redis_store.get('qh_up_price_eth')) + float(price)
            redis_store.set('qh_up_price_eth', up_price)
        if uid == 2:
            flat_price = float(redis_store.get('qh_flat_price_eth')) + float(price)
            redis_store.set('qh_flat_price_eth', flat_price)
        if uid == 3:
            down_price = float(redis_store.get('qh_down_price_eth')) + float(price)
            redis_store.set('qh_down_price_eth', down_price)
        # 检查该用户该期是否在该类型有下注
        bet = qhjy_db.selectone(
            "select * from qhjy.qh_betting where user_id=%d and tw_qh_coin=24 and nper_id=%d and `type`=%d" % (
            user_id, nper_id, uid))
        # 没下注
        if not bet:
            sql = 'insert into qhjy.qh_betting(user_id,tw_qh_coin,nper_id,`type`,price,add_time,is_true) values({},24,{},{},{},{},1);'.format(
                user_id, nper_id, uid, price, int(time.time()))
            qhjy_db.execute(sql)
            qhjy_db.execute(
                'insert into qh_betting_false VALUE (0,{},{},{},{},{},{},{})'.format(user_id, session["mobile"], price,
                                                                                     uid, 24, nper_id, 0.1,
                                                                                     int(time.time())))
        # 下注
        else:
            price = bet["price"] + price
            sql = 'update qhjy.qh_betting set price=%f,add_time=%d where id=%d' % (price, int(time.time()), bet["id"])
            qhjy_db.execute(sql)
        sql = 'insert into qhjy.qh_betting(user_id,tw_qh_coin,nper_id,`type`,price,add_time,is_true) values({},3,{},{},{},{},1);'.format(
            user_id, nper_id, uid, price, int(time.time()))
        print(sql)
        qhjy_db.execute(sql)
        bet = qhjy_db.selectone(
            "select * from qhjy.qh_betting where user_id=%d and tw_qh_coin=24 and nper_id=%d and `type`=%d" % (
            user_id, nper_id, uid))
        decimal_to_float(bet)
        # redis个人投注记录
        # redis_store.set('user_betting_record_to_w_%s_3'%str(session["id"]), jsonify(bet))
        # if redis_store.llen('qh_ecord_betting')>=100:
        #     redis_store.lpop("qh_ecord_betting")
        redis_store.lpush("qh_ecord_betting", json.dumps([mobile, float(price), uid, 24, int(time.time()), 0.1]))
        redis_store.lpush("qh_ecord_betting2", json.dumps([mobile, float(price), uid, 24, int(time.time()), 0.1]))
        # 冻结资金
        new_eth = finance['eth'] - price
        new_ethd = finance['ethd'] + price
        jys_db.execute('update bf_user_coin set eth={},ethd={} where userid={}'.format(new_eth, new_ethd, user_id))
        # 搜集返回的数据(期号,买了涨跌平,是BTC还是ETH,多少,多长时间会交割)
        mdict = {}
        mdict["nper"] = nper["nper"]
        mdict["t"] = nper["open_time"] + 600
        mdict["price"] = float(price)
        mdict["type"] = "ETH"
        mdict["status"] = uid
        return jsonify({'code': 1, 'datas': mdict, 'msg': '投注成功'})
    else:
        return jsonify({'code': 0, 'data': '', 'msg': '用户未登录,请先登录'})


# 涨,平,跌赔率接口
@eth_qhjy.route('/vote/', methods=['GET', 'POST'])
def vote():
    redis_store = redis.Redis(connection_pool=pool)
    res = {}
    up = round(float(redis_store.get('qh_up_price_eth')), 4)
    flat = round(float(redis_store.get('qh_flat_price_eth')), 4)
    down = round(float(redis_store.get('qh_down_price_eth')), 4)
    all = round(up + flat + down, 4)
    # res=qhjy_db.selectone('select up_rate,down_rate,flat_rate from qh_nper where coin_id=3 and is_current = 1 ')
    if up:
        res['up_rate'] = '{0:.2%}'.format(float(all / up))
    else:
        res['up_rate'] = "300%"
    if down:
        res['down_rate'] = '{0:.2%}'.format(float(all / down))
    else:
        res['down_rate'] = "300%"
    if flat:
        res["flat_rate"] = '{0:.2%}'.format(float(all / flat))
    else:
        res['flat_rate'] = "300%"
    return jsonify({'code': 1, 'data': res, 'msg': ''})


# 买涨,买平,买跌总数量
@eth_qhjy.route('/aaa/', methods=['GET', 'POST'])
def aaa():
    # token=request.cookies.get('token',None)
    # if token and check_activate_token(token) == session['id']:
    redis_store = redis.Redis(connection_pool=pool)
    mdict = {}
    mdict["up"] = round(float(redis_store.get('qh_up_price_eth')), 4)
    mdict["flat"] = round(float(redis_store.get('qh_flat_price_eth')), 4)
    mdict["down"] = round(float(redis_store.get('qh_down_price_eth')), 4)
    mdict["all"] = round(mdict["up"] + mdict["flat"] + mdict["down"], 4)
    eth_price = float(jys_db.selectone('select price from tw_eth where short_name="CNY"')["price"])
    mdict["allCNY"] = int(eth_price * float(mdict["all"]))
    return jsonify({'code': 1, 'data': mdict, 'msg': ''})
    # else:
    #     return jsonify({'code': 0, 'data': '', 'msg': '用户没登录'})


# 当前结果(期号,点差,d)
@eth_qhjy.route('/now_result/', methods=['GET', 'POST'])
def now_result():
    minute = datetime.now().minute
    if minute % 10 == 7 or minute % 10 == 2:
        sql = 'select qh_result.*,qh_nper.nper,qh_nper.result,qh_nper.result_rate,qh_nper.open_time from qh_result INNER  join qh_nper on qh_result.nper_id=qh_nper.id where qh_nper.coin_id=24 and qh_nper.is_current=2  and qh_result.exchange_name in (1,2,3,6,7) and qh_nper.result!=0 GROUP by qh_result.exchange_name ORDER by qh_result.exchange_name'
        res = qhjy_db.selectall(sql)
        # end = int(time.time())
        # if end - res["open"] - 600 > 60:
        #     sql = 'update qhjy.qh_config set btc_error=1 '
        #     qhjy_db._Connection__execute(sql)
        #     return jsonify({'code': -1, 'datas': '', 'msg': '数据超时'})
        if res:
            if len(res) == 5:
                for r in res:
                    r['rose'], r["consequence"] = compute_gains(r['open_time_price'], r['end_time_price'])
                    for k, v in r.items():
                        if isinstance(v, Decimal):
                            r[k] = str(round(v, 2))
                redis_store = redis.Redis(connection_pool=pool)
                redis_store.set('eth_latest_result', json.dumps(res))
                print(datetime.now(), '当前ETH数据')
                print(res)
                return jsonify({'code': 1, 'datas': res, 'msg': '返回当前数据'})
            else:
                return jsonify({'code': 0, 'datas': '', 'msg': '数据不够'})
        else:
            return jsonify({'code': 0, 'datas': '', 'msg': '没有数据'})
    else:
        return jsonify({'code': 0, 'data': "", 'msg': '还没到交割时间呢'})


# 最近一期七家交易所BTC数据(期号,张平,点差)
@eth_qhjy.route('/latest_result/', methods=['GET', 'POST'])
def latest_result():
    sql = "select id,nper,result,result_rate from qh_nper where is_current!=1 and result!=0 and coin_id=24 order by id desc"
    # sql='select qh_result.*,qh_nper.nper,qh_nper.result,qh_nper.result_rate from qh_result INNER  join qh_nper on qh_result.nper_id=qh_nper.id where qh_nper.coin_id=3 and qh_nper.is_current in (0,2) and qh_nper.id in (select A.id from (select id from qh_nper where qh_nper.coin_id=3 and is_current in (0,2) ORDER by id DESC limit 10) as A) '
    nper = qhjy_db.selectone(sql)
    if nper:
        sql = 'select * from qh_result where nper_id=%d and exchange_name in (1,2,3,6,7) GROUP by exchange_name ORDER by exchange_name' % (
            nper["id"])
        datas = qhjy_db.selectall(sql)
        if datas:
            for r in datas:
                if r:
                    r['rose'], r["consequence"] = compute_gains(r['open_time_price'], r['end_time_price'])
                    r["result"] = nper["result"]
                    r["result_rate"] = nper["result_rate"]
                    r["nper"] = nper["nper"]
                    for k, v in r.items():
                        if isinstance(v, Decimal):
                            r[k] = str(round(v, 2))
            return jsonify({'code': 1, 'datas': datas, 'msg': '返回最新十期数据'})
        else:
            return jsonify({'code': 0, 'datas': '', 'msg': '数据出错了'})
    else:
        return jsonify({'code': 0, 'datas': '', 'msg': '数据出错了'})
    # redis_store = redis.Redis(connection_pool=pool)
    # data=redis_store.get('eth_latest_result')
    # print("ETH数据",data)
    # if data:
    #     print(datetime.now(),'redis中获取ETH最近一期的数据')
    #     res=json.loads(data.decode("utf-8"))
    #     return jsonify({'code': 1, 'datas': res, 'msg': '返回最新数据'})
    # else:
    #     res = qhjy_db.selectall('select qh_result.*,qh_nper.nper,qh_nper.result,qh_nper.result_rate from qh_result INNER  join qh_nper on qh_result.nper_id=qh_nper.id where qh_nper.coin_id=24 and qh_nper.is_current = 2 and qh_result.exchange_name in (1,2,3,6,7) GROUP by qh_result.exchange_name ORDER by qh_result.exchange_name')
    #     # res = qhjy_db.selectall('select qh_result.*,qh_nper.nper,qh_nper.result,qh_nper.result_rate from qh_result INNER  join qh_nper on qh_result.nper_id=qh_nper.id where qh_nper.coin_id=24 and qh_nper.is_current = 2')
    #     for r in res:
    #         r['rose'], r["consequence"] = compute_gains(r['open_time_price'], r['end_time_price'])
    #         for k, v in r.items():
    #             if isinstance(v, Decimal):
    #                 r[k] = str(round(v, 2))
    #     return  jsonify({'code': 1, 'datas': res, 'msg': '返回最新数据'})


# 币安交易所开始
@eth_qhjy.route('/global_market/', methods=['GET', 'POST'])
def global_market():
    return jsonify({'code': 0, 'datas': getETHBinance(), 'msg': '查询不到最新一期的期号'})


# 币安交易所一分钟
@eth_qhjy.route('/global_market_one/', methods=['GET', 'POST'])
def global_market_one():
    return jsonify({'code': 0, 'datas': getETHBinanceForOne(), 'msg': '查询不到最新一期的期号'})


# 倒计时
'''
通知开盘
btc结果通知后续操作(结果要存到nper里面)
'''


@eth_qhjy.route('/last/', methods=['GET', 'POST'])
def last():
    # redis_store = redis.Redis(connection_pool=pool)
    # t = redis_store.get("qh_current_time_info_24")
    # # print(redis_store.keys("user_betting_record_to_w_*_3"))
    # if t:
    #     data = json.loads(t.decode('utf-8'))
    # else:
    data = qhjy_db.selectone(
        'select a.end_time,a.open_time,b.end_time as next_end_time,b.stop_time as next_stop_time,a.stop_time,c.nper,b.nper as next_nper from (select nper,end_time,open_time,stop_time from qh_nper where is_current=1 and coin_id=24) a,(select nper,end_time,open_time,stop_time from qh_nper where is_current=3 and coin_id=24) b,(select nper,end_time,open_time,stop_time from qh_nper where is_current=2 and coin_id=24) c')
    if data:
        data["current_time"] = int(time.time())
        return jsonify({'code': 1, 'data': data, 'msg': ''})
    else:
        return jsonify({'code': 0, 'data': '', 'msg': '没有数据'})
        # data = qhjy_db.selectone('select a.end_time,a.open_time,b.end_time as next_end_time,b.stop_time as next_stop_time,a.stop_time,a.nper,b.nper as next_nper from (select nper,end_time,open_time,stop_time from qh_nper where is_current=1 and coin_id=3) a,(select nper,end_time,open_time,stop_time from qh_nper where is_current=3 and coin_id=3) b')

        # if data:
        #     data["current_time"] = int(time.time())
        #     return jsonify({'code': 1, 'data': data, 'msg': ''})
        # else:
        #     return jsonify({'code': 0, 'data': '', 'msg': ''})
